# _*_ coding:utf-8 _*_
# @File  : other.py
# @Time  : 2021-08-09  09:49
# @Author: zizle

from fastapi import APIRouter, Depends, Body, Query
from db import FAConnection
from status import r_status
from hutool.utils import list2tree
from interfaces.depends import logged_require

other_api = APIRouter()


# 获取某个用户的建议反馈
@other_api.get('/suggest/', summary='获取某个用户的建议反馈')
async def get_user_suggest(person: dict = Depends(logged_require), page: int = Query(1, ge=1),
                           page_size: int = Query(10, ge=10, le=100)):
    record_start = (page - 1) * page_size
    record_offset = page_size

    sql = 'SELECT SQL_CALC_FOUND_ROWS a.id,a.create_time,a.author_id,b.username,a.suggest,a.parent_id ' \
          'FROM sys_user_suggest AS a ' \
          'INNER JOIN user_user AS b ON a.author_id=b.id ' \
          'WHERE a.author_id=%s AND a.parent_id=0 ' \
          'ORDER BY a.create_time DESC LIMIT %s,%s;'
    db = FAConnection(conn_name='用户查询交流反馈')
    records = db.query(sql, [person['uid'], record_start, record_offset], keep_conn=True)
    total_obj = db.query('SELECT FOUND_ROWS() AS total;', fetchone=True, keep_conn=True)
    total_count = total_obj[0]['total'] if total_obj else 0  # 当前总数量
    # 查询回复
    p_id = [r['id'] for r in records]
    if len(p_id) > 0:
        reply_sql = 'SELECT a.id,a.create_time,a.author_id,b.username,a.suggest,a.parent_id ' \
                    'FROM sys_user_suggest AS a ' \
                    'INNER JOIN user_user AS b ON a.author_id=b.id ' \
                    'WHERE a.parent_id in %s;'
        child = db.query(reply_sql, param=[p_id])
        records = records + child
    else:
        db.close()
    for item in records:
        item['create_time'] = item['create_time'].strftime('%Y-%m-%d %H:%M:%S')
    records = list2tree(records, 0)
    return {'code': r_status.SUCCESS, 'message': '查询建议记录!', 'page': page, 'page_size': page_size,
            'total_count': total_count, 'data': records}


# 添加一条建议反馈
@other_api.post('/suggest/', summary='添加一条建议反馈')
async def add_suggest(person: dict = Depends(logged_require), content: str = Body(..., embed=True),
                      parent_id: int = Body(0, ge=0)):
    author_id = person['uid']
    sql = 'INSERT INTO sys_user_suggest (author_id,suggest,parent_id) VALUES (%s,%s,%s);'
    db = FAConnection(conn_name='添加系统建议')
    count, _ = db.insert(sql, [author_id, content, parent_id])
    if count:
        return {'code': r_status.CREATED_SUCCESS, 'message': '添加建议成功!'}
    return {'code': r_status.VALIDATE_ERROR, 'message': '添加建议失败了!'}


